package com.wlr.study.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class LeetCode22 {

    public List<String> generateParenthesis(int n) {
        List<List<String>> lists = new ArrayList<>();
        lists.add(new ArrayList<>(Arrays.asList("")));// n=0
        lists.add(new ArrayList<>(Arrays.asList("()")));// n=1
        for (int i = 2; i <= n; i++) {
            List<String> list = new ArrayList<>();
            // 先拿出一个括号x，剩下的i-1个括号分为x内部和x外部
            for (int in = 0; in <= i - 1; in++) {
                int out = i - 1 - in;
                for (String inStr : lists.get(in)) {
                    for (String outStr : lists.get(out)) {
                        list.add("(" + inStr + ")" + outStr);
                    }
                }
            }
            lists.add(list);
        }
        return new ArrayList<>(lists.get(n));
    }
    public List<String> generateParenthesis1(int n) {
        List<String> combinations = new ArrayList<String>();
        generateAll(new char[2 * n], 0, combinations);
        return combinations;
    }

    public void generateAll(char[] current, int pos, List<String> result) {
        if (pos == current.length) {
            if (valid(current)) {
                result.add(new String(current));
            }
        } else {
            current[pos] = '(';
            generateAll(current, pos + 1, result);
            current[pos] = ')';
            generateAll(current, pos + 1, result);
        }
    }

    public boolean valid(char[] current) {
        int balance = 0;
        for (char c: current) {
            if (c == '(') {
                ++balance;
            } else {
                --balance;
            }
            if (balance < 0) {
                return false;
            }
        }
        return balance == 0;
    }

    public static void main(String[] args) {
        LeetCode22 leetCode22 = new LeetCode22();
        System.out.println(leetCode22.generateParenthesis1(3));
    }

}
